import React, { Component } from 'react'

import { Query, graphql } from 'react-apollo'
import gql from 'graphql-tag'

import {
  Dimensions,
  Image,
  ScrollView,
  StyleSheet,
  TouchableOpacity,
} from 'react-native'
import { inject, observer } from 'mobx-react/native'
import { Carousel, Grid, SearchBar } from 'antd-mobile'
import { Icon } from '../components'
import { variables } from '../styles'

const icon = (
  <Icon
    name={'ribbon'}
    size={variables.icon_size_lg}
    color={variables.color_text_caption}
  />
)

const grids = cs => [
  { text: 'All', icon },
  ...cs.map(c => ({ ...c, text: c.title, icon })),
]

const QUERY_HOT_ITEMS = gql`
  query {
    allItems(first: 5, orderBy: updatedAt_DESC) {
      id
      title
      images
    }
  }
`

const QUERY_CATEGORIES = gql`
  query {
    allItemCategories {
      id
      title
    }
  }
`

const mockImage = i =>
  [
    'https://zos.alipayobjects.com/rmsportal/TekJlZRVCjLFexlOCuWn.png',
    'https://zos.alipayobjects.com/rmsportal/AiyWuByWklrrUDlFignR.png',
    'https://zos.alipayobjects.com/rmsportal/IJOtIlfsYdTyaDTRVrLI.png',
  ][i % 3]

@inject('actions', 'store')
@observer
export class HomeScreen extends Component {
  render = () => (
    <ScrollView style={styles.container}>
      <SearchBar
        placeholder="Search"
        onSubmit={search => this.props.navigation.navigate('Items', { search })}
      />
      <Query query={QUERY_HOT_ITEMS} fetchPolicy="network-only">
        {({ loading, data: { ['allItems']: items } = {} }) =>
          !loading &&
          items.length > 0 && (
            <Carousel infinite>
              {(items || []).map((item, i) => (
                <TouchableOpacity
                  key={item.id}
                  onPress={() =>
                    this.props.navigation.navigate('Item', { id: item.id })
                  }
                >
                  <Image
                    style={{
                      width: Dimensions.get('window').width,
                      height: 200,
                    }}
                    source={{
                      uri: (item.images && item.images[0]) || mockImage(i),
                    }}
                  />
                </TouchableOpacity>
              ))}
            </Carousel>
          )
        }
      </Query>
      <Query query={QUERY_CATEGORIES}>
        {({ loading, data: { ['allItemCategories']: categories } = {} }) =>
          !loading && (
            <Grid
              data={grids(categories || [])}
              hasLine={false}
              onClick={({ id }) =>
                this.props.navigation.navigate('Items', { categoryId: id })
              }
            />
          )
        }
      </Query>
    </ScrollView>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
})
